//
// AWS Manager - A free AWS console application demonstrating advanced concepts
// Copyright (C) 2008-2010 Sean O'Dell. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package awsmanager;

import com.awsmanager.common.EC2IP;
import com.awsmanager.common.EC2Instance;
import com.awsmanager.common.AWSObjectUtils;
import com.sun.data.provider.RowKey;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.webui.jsf.component.Alert;
import com.sun.webui.jsf.component.Checkbox;
import com.sun.webui.jsf.component.DropDown;
import com.sun.webui.jsf.component.Form;
import com.sun.webui.jsf.component.TabSet;
import com.sun.webui.jsf.component.TextField;
import com.sun.webui.jsf.model.Option;
import java.util.ArrayList;
import javax.faces.FacesException;
import javax.faces.event.ValueChangeEvent;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @version EC2AssociateIP.java
 * @version Created on Nov 23, 2008, 2:14:36 PM
 * @author Sean ODell
 */
public class EC2AssociateIP extends AbstractPageBean {
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    private DropDown ddl_InstanceIds = new DropDown();

    public DropDown getDdl_InstanceIds() {
        return ddl_InstanceIds;
    }

    public void setDdl_InstanceIds(DropDown dd) {
        this.ddl_InstanceIds = dd;
    }
    private TextField tf_InstanceID = new TextField();

    public TextField getTf_InstanceID() {
        return tf_InstanceID;
    }

    public void setTf_InstanceID(TextField tf) {
        this.tf_InstanceID = tf;
    }
    private TextField tf_InstanceName = new TextField();

    public TextField getTf_InstanceName() {
        return tf_InstanceName;
    }

    public void setTf_InstanceName(TextField tf) {
        this.tf_InstanceName = tf;
    }
    private TextField tf_IPName = new TextField();

    public TextField getTf_IPName() {
        return tf_IPName;
    }

    public void setTf_IPName(TextField tf) {
        this.tf_IPName = tf;
    }
    private TextField tf_IPAddress = new TextField();

    public TextField getTf_IPAddress() {
        return tf_IPAddress;
    }

    public void setTf_IPAddress(TextField tf) {
        this.tf_IPAddress = tf;
    }
    private Alert al_EC2AssociateIP = new Alert();

    public Alert getAl_EC2AssociateIP() {
        return al_EC2AssociateIP;
    }

    public void setAl_EC2AssociateIP(Alert a) {
        this.al_EC2AssociateIP = a;
    }
    private TextField tf_CurrentInstanceID = new TextField();

    public TextField getTf_CurrentInstanceID() {
        return tf_CurrentInstanceID;
    }

    public void setTf_CurrentInstanceID(TextField tf) {
        this.tf_CurrentInstanceID = tf;
    }
    private TextField tf_CurrentInstanceName = new TextField();

    public TextField getTf_CurrentInstanceName() {
        return tf_CurrentInstanceName;
    }

    public void setTf_CurrentInstanceName(TextField tf) {
        this.tf_CurrentInstanceName = tf;
    }
    private Checkbox cb_OverrideCurrent = new Checkbox();

    public Checkbox getCb_OverrideCurrent() {
        return cb_OverrideCurrent;
    }

    public void setCb_OverrideCurrent(Checkbox c) {
        this.cb_OverrideCurrent = c;
    }
    protected Option[] instanceIDsOptions;

    /**
     * Get the value of instanceIDsOptions
     *
     * @return the value of instanceIDsOptions
     */
    public Option[] getInstanceIDsOptions() {
        return instanceIDsOptions;
    }

    /**
     * Set the value of instanceIDsOptions
     *
     * @param instanceIDsOptions new value of instanceIDsOptions
     */
    public void setInstanceIDsOptions(Option[] instanceIDsOptions) {
        this.instanceIDsOptions = instanceIDsOptions;
    }
    protected Boolean overrideAssociationVisible;

    /**
     * Get the value of overrideAssociationVisible
     *
     * @return the value of overrideAssociationVisible
     */
    public Boolean getOverrideAssociationVisible() {
        return overrideAssociationVisible;
    }

    /**
     * Set the value of overrideAssociationVisible
     *
     * @param overrideAssociationVisible new value of overrideAssociationVisible
     */
    public void setOverrideAssociationVisible(Boolean overrideAssociationVisible) {
        this.overrideAssociationVisible = overrideAssociationVisible;
    }
    protected Boolean associateButtonVisible;

    /**
     * Get the value of associateButtonVisible
     *
     * @return the value of associateButtonVisible
     */
    public Boolean getAssociateButtonVisible() {
        return associateButtonVisible;
    }

    /**
     * Set the value of associateButtonVisible
     *
     * @param associateButtonVisible new value of associateButtonVisible
     */
    public void setAssociateButtonVisible(Boolean associateButtonVisible) {
        this.associateButtonVisible = associateButtonVisible;
    }
    private Form form1 = new Form();

    public Form getForm1() {
        return form1;
    }

    public void setForm1(Form f) {
        this.form1 = f;
    }


    // </editor-fold>
    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public EC2AssociateIP() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("EC2AssociateIP Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }

    // </editor-fold>
    // Perform application initialization that must complete
    // *after* managed components are initialized
    // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {

        ArrayList ec2instanceavaillist = new ArrayList();
        RowKey[] selectedRowKeys = getSessionBean1().getSelectedRowKeys();
        setOverrideAssociationVisible(false);
        EC2Instance ec2instance = null;

        if (selectedRowKeys.length > 0) {

            // get information for the IP address to associate.
            String rowId = selectedRowKeys[0].getRowId();
            RowKey rowKey = getSessionBean1().getEc2IPDataProvider().getRowKey(rowId);
            EC2IP ec2ip = getSessionBean1().getEc2IPDataProvider().getEC2IP(rowKey);

            // get a list of all instance ids
            ArrayList ec2instancelist =
                    getSessionBean1().getEC2InstanceDataProvider().getEC2InstanceIDsList();

            // check each instance id to see if associated to an Elastic IP
            // already or not. If not, and in same region, add to list of
            //available instance ids.

            boolean atLeastOneInstanceInRegion = false;

            for (int i = 0; i < ec2instancelist.size(); i++) {
                ec2instance = getSessionBean1().getEC2InstanceDataProvider().getInstance((String) ec2instancelist.get(i));
                if ((!getSessionBean1().getEc2IPDataProvider().isInstanceIDUsed(ec2instance.getinstanceId()) && (ec2instance.getstateName().equals("running")))) {
                    if (ec2instance.getInstanceRegion().equals(ec2ip.getRegion())) {
                        ec2instanceavaillist.add(ec2instancelist.get(i));
                        atLeastOneInstanceInRegion = true;
                    }
                }
            }

            // create the drop down list options from list of available
            // instance ids.
            instanceIDsOptions = new Option[ec2instanceavaillist.size() + 1];
            instanceIDsOptions[0] = new Option("Select Instance ID");
            if (ec2instanceavaillist.size() >= 1) {
                setAssociateButtonVisible(true);
                for (int i = 0; i < ec2instanceavaillist.size(); i++) {
                    ec2instance = getSessionBean1().getEC2InstanceDataProvider().getInstance((String) ec2instanceavaillist.get(i));
                    String strInstanceRef = new String((String) ec2instanceavaillist.get(i));
                    if (ec2instance.getinstname() != null) {
                        if (!ec2instance.getinstname().equals("")) {
                            strInstanceRef = strInstanceRef + " (" + ec2instance.getinstname() + ")";
                        }
                    }
                    instanceIDsOptions[i + 1] = new Option(strInstanceRef);
                }
            } else {
                al_EC2AssociateIP.setSummary("No instances are available for association.");
                setAssociateButtonVisible(false);
            }

            // set options.
            if (ec2ip != null) {
                if (ec2ip.getpublicip() != null) {
                    tf_IPAddress.setText(ec2ip.getpublicip());
                }
                if (ec2ip.geteipname() != null) {
                    tf_IPName.setText(ec2ip.geteipname());
                }
                if (ec2ip.getinstanceId() != null) {
                    tf_CurrentInstanceID.setText(ec2ip.getinstanceId());
                    if (!ec2ip.getinstanceId().equals("")) {
                        setOverrideAssociationVisible(true);
                    }
                }
                if (ec2ip.geteipinstancename() != null) {
                    tf_CurrentInstanceName.setText(ec2ip.geteipinstancename());
                }
            }
        }
    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    public void ddl_InstanceIds_processValueChange(ValueChangeEvent event) {

        AWSObjectUtils awsObjectUtils = new AWSObjectUtils();
        EC2Instance ec2instance = null;
        String instanceName = null;

        String selectedInstanceID =
                awsObjectUtils.idExtract((String) ddl_InstanceIds.getSelected());

        ec2instance = getSessionBean1().getEC2InstanceDataProvider().getInstance((String) selectedInstanceID);

        if (ec2instance != null) {
            if ((instanceName = ec2instance.getinstname()) == null) {
                instanceName = "";
            }
        }

        tf_InstanceID.setText(selectedInstanceID);
        tf_InstanceName.setText(instanceName);

        if ((selectedInstanceID == null) || (selectedInstanceID.equals("")) || (selectedInstanceID.equals("Select Instance ID"))) {
            al_EC2AssociateIP.setSummary("Please select an instance id from the list.");
        } else {
            al_EC2AssociateIP.setSummary("");
        }
    }

    public String returnBtn_action() {
        TabSet tabSet = getSessionBean1().getCurrentTabSet();
        if (tabSet != null) {
            tabSet.setSelected("EC2_IPs");
            getSessionBean1().setCurrentTabSet(tabSet);
        }
        return "return";
    }

    public String associateBtn_action() {

        TabSet tabSet = getSessionBean1().getCurrentTabSet();
        RowKey[] selectedRowKeys = getSessionBean1().getSelectedRowKeys();
        Boolean overrideIschecked = getCb_OverrideCurrent().isChecked();

        AWSObjectUtils awsObjectUtils = new AWSObjectUtils();
        String selectedInstanceID =
                awsObjectUtils.idExtract((String) ddl_InstanceIds.getSelected());

        if ((selectedInstanceID == null)) {
            al_EC2AssociateIP.setSummary("Please select an instance id from the list.");
            return null;
        } else if ((selectedInstanceID.equals("")) || (selectedInstanceID.equals("Select Instance ID"))) {
            al_EC2AssociateIP.setSummary("Please select an instance id from the list.");
            return null;
        } else {
            al_EC2AssociateIP.setSummary("");
        }

        // get information for the IP address to associate and set options.
        String rowId = selectedRowKeys[0].getRowId();
        RowKey rowKey = getSessionBean1().getEc2IPDataProvider().getRowKey(rowId);
        EC2IP ec2ip = getSessionBean1().getEc2IPDataProvider().getEC2IP(rowKey);

        if (ec2ip != null) {
            if (ec2ip.getinstanceId() != null) {
                if (!ec2ip.getinstanceId().equals("") &&
                        !overrideIschecked) {
                    al_EC2AssociateIP.setSummary("The Elastic IP is already associated. Select the \"Override\" option if you really want to contine.");
                    return null;
                } else {
                    al_EC2AssociateIP.setSummary("");
                }
            }
            getSessionBean1().getEc2IPDataProvider().associateEC2IP(selectedInstanceID,
                    ec2ip.getpublicip(), ec2ip.getRegion());
        }

        if (tabSet != null) {
            tabSet.setSelected("EC2_IPs");
            getSessionBean1().setCurrentTabSet(tabSet);
        }

        getSessionBean1().getEc2IPDataProvider().load(getSessionBean1().getEc2Connection(),
                getSessionBean1().getSdbConnection(),
                getSessionBean1().getEC2InstanceDataProvider());

        return "return";
    }
}